<template>
	<div id="picture-detail-view">
		<a-row :gutter="[16, 16]">
			<!-- 图片预览 -->
			<a-col :sm="24" :md="14" :xl="16">
				<a-card title="图片预览">
					<a-image :src="picture?.url" style="max-height: 600px; object-fit: contain" />
				</a-card>
			</a-col>
			<!-- 图片信息区 -->
			<a-col :sm="24" :md="10" :xl="8">
				<a-card title="图片信息">
					<a-descriptions :column="1">
						<a-descriptions-item label="作者">
							<a-space>
								<a-avatar :size="24" :src="picture?.user?.userAvatar" />
								<div>{{ picture?.user?.userName }}</div>
							</a-space>
						</a-descriptions-item>
						<a-descriptions-item label="名称">
							{{ picture?.name ?? '未命名' }}
						</a-descriptions-item>
						<a-descriptions-item label="简介">
							{{ picture?.introduction ?? '-' }}
						</a-descriptions-item>
						<a-descriptions-item label="分类">
							{{ picture?.category ?? '默认' }}
						</a-descriptions-item>
						<a-descriptions-item label="标签">
							<a-tag v-for="tag in picture?.tags" :key="tag">
								{{ tag }}
							</a-tag>
						</a-descriptions-item>
						<a-descriptions-item label="格式">
							{{ picture?.picFormat ?? '-' }}
						</a-descriptions-item>
						<a-descriptions-item label="宽度">
							{{ picture?.picWidth ?? '-' }}
						</a-descriptions-item>
						<a-descriptions-item label="高度">
							{{ picture?.picHeight ?? '-' }}
						</a-descriptions-item>
						<a-descriptions-item label="宽高比">
							{{ picture?.picScale ?? '-' }}
						</a-descriptions-item>
						<a-descriptions-item label="大小">
							{{ formatSize(picture?.picSize as number) }}
						</a-descriptions-item>
						<a-descriptions-item label="主色调">
							<a-space>
								{{ picture?.picColor ?? '-' }}
								<div
									v-if="picture?.picColor"
									:style="{
										backgroundColor: toHexColor(picture?.picColor),
										width: '16px',
										height: '16px',
									}"
								/>
							</a-space>
						</a-descriptions-item>

						<a-descriptions-item label="审核状态" v-if="isAdmin">
							<a-tag
								:color="
									pictureDetail?.reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS
										? 'green'
										: pictureDetail?.reviewStatus === PIC_REVIEW_STATUS_ENUM.REJECT
										? 'red'
										: 'orange'
								"
							>
								{{ PIC_REVIEW_STATUS_MAP[pictureDetail?.reviewStatus ?? PIC_REVIEW_STATUS_ENUM.REVIEWING] }}
							</a-tag>
						</a-descriptions-item>
						<a-descriptions-item label="审核信息" v-if="isAdmin && pictureDetail?.reviewMessage">
							{{ pictureDetail?.reviewMessage }}
						</a-descriptions-item>
					</a-descriptions>
					<a-space wrap>
						<a-button type="primary" :icon="h(DownloadOutlined)" @click="doDownload"> 免费下载 </a-button>
						<a-button :icon="h(ShareAltOutlined)" type="primary" @click="doShare"> 分享 </a-button>
						<a-button v-if="canEdit" :icon="h(EditOutlined)" type="primary" @click="doEdit"> 编辑 </a-button>
						<a-button v-if="canDelete" :icon="h(DeleteOutlined)" danger @click="doDelete"> 删除 </a-button>
						<!-- 管理员审核按钮 -->
						<a-button
							v-if="canPassReview && picture?.spaceId == undefined"
							:icon="h(CheckOutlined)"
							type="primary"
							style="background: #52c41a; border-color: #52c41a"
							@click="handleReview(PIC_REVIEW_STATUS_ENUM.PASS)"
						>
							审核通过
						</a-button>
						<a-button
							v-if="canRejectReview && picture?.spaceId == undefined"
							:icon="h(CloseOutlined)"
							danger
							@click="handleReview(PIC_REVIEW_STATUS_ENUM.REJECT)"
						>
							审核拒绝
						</a-button>
					</a-space>
				</a-card>
			</a-col>
		</a-row>

		<!-- 审核弹窗 -->
		<a-modal
			v-model:open="reviewModalVisible"
			:title="`${currentReviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '审核通过' : '审核拒绝'} - ${picture?.name}`"
			:confirmLoading="reviewModalLoading"
			@ok="handleReviewConfirm"
			@cancel="handleReviewCancel"
			width="500px"
		>
			<a-form :model="reviewForm" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
				<a-form-item label="图片信息">
					<div class="review-picture-info">
						<a-image v-if="picture?.url" :src="picture.thumbnailUrl || picture.url" :width="100" />
						<div class="picture-details">
							<p><strong>名称：</strong>{{ picture?.name }}</p>
							<p><strong>类型：</strong>{{ picture?.category }}</p>
							<p><strong>简介：</strong>{{ picture?.introduction }}</p>
						</div>
					</div>
				</a-form-item>
				<a-form-item label="审核意见" name="reviewMessage" :rules="[{ required: true, message: '请填写审核意见!' }]">
					<a-textarea
						v-model:value="reviewForm.reviewMessage"
						:placeholder="`请填写${currentReviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '通过' : '拒绝'}的理由`"
						:rows="4"
						:max-length="200"
						show-count
					/>
				</a-form-item>
			</a-form>
		</a-modal>
		<ShareModal ref="shareModalRef" title="分享图片" :link="shareLink" />
	</div>
</template>

<script setup lang="ts">
import {
	deletePictureUsingPost,
	getPictureVoByIdUsingGet,
	doPictureReviewUsingPost,
	getPictureByIdUsingGet,
} from '@/api/pictureController'
import { message, Modal } from 'ant-design-vue'
import { onMounted, ref, h, computed, reactive } from 'vue'
import {
	EditOutlined,
	DeleteOutlined,
	DownloadOutlined,
	CheckOutlined,
	CloseOutlined,
	ShareAltOutlined,
} from '@ant-design/icons-vue'
import { downloadImage, formatSize } from '@/utils'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { useRouter } from 'vue-router'
import { PIC_REVIEW_STATUS_ENUM, PIC_REVIEW_STATUS_MAP } from '@/constants/picture'
import { createVNode } from 'vue'
import { toHexColor } from '@/utils'
import ShareModal from '@/components/modal/ShareModal.vue'
import ACCESS_ENUM from '@/access/accessEnum'
import { SPACE_PERMISSION_ENUM } from '@/constants/space'

interface Props {
	id: string | number
}

const props = defineProps<Props>()
const picture = ref<API.PictureVO>()
const pictureDetail = ref<API.Picture>() // 包含审核状态的完整图片信息

// 通用权限检查函数
function createPermissionChecker(permission: string) {
	return computed(() => {
		return (picture.value?.permissionList ?? []).includes(permission)
	})
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.PICTURE_DELETE)

// 审核弹窗相关状态
const reviewModalVisible = ref(false)
const reviewModalLoading = ref(false)
const currentReviewStatus = ref<number>()
const reviewForm = reactive({
	reviewMessage: '',
})

// 获取图片数据
const route = useRouter()
const fetchPictureDetail = async () => {
	try {
		// 获取展示用的图片信息
		const res = await getPictureVoByIdUsingGet({ id: props.id as any })
		if (res.data.code === 0 && res.data.data) {
			picture.value = res.data.data
		} else {
			message.error('获取图片详情失败：' + res.data.message)
			route.push('/')
			return
		}

		// 只有管理员才需要获取包含审核状态的完整图片信息
		const loginUser = loginUserStore.loginUser
		if (loginUser.userRole === ACCESS_ENUM.ADMIN) {
			const detailRes = await getPictureByIdUsingGet({ id: props.id as any })
			if (detailRes.data.code === 0 && detailRes.data.data) {
				pictureDetail.value = detailRes.data.data
			}
		}
	} catch (error: any) {
		message.error('获取图片详情失败：' + error.message)
		route.push('/')
	}
}

const loginUserStore = useLoginUserStore()

// 是否是管理员
const isAdmin = computed(() => {
	const loginUser = loginUserStore.loginUser
	return loginUser.userRole === ACCESS_ENUM.ADMIN
})

// 是否可以审核
const canReview = computed(() => {
	return isAdmin.value && picture.value?.id
})

// 是否可以通过审核（仅当图片不是已通过状态时显示）
const canPassReview = computed(() => {
	return canReview.value && pictureDetail.value?.reviewStatus !== PIC_REVIEW_STATUS_ENUM.PASS
})

// 是否可以拒绝审核（仅当图片不是已拒绝状态时显示）
const canRejectReview = computed(() => {
	return canReview.value && pictureDetail.value?.reviewStatus !== PIC_REVIEW_STATUS_ENUM.REJECT
})

// 编辑
const router = useRouter()
const doEdit = () => {
	// 如果是公共图库，则不传递空间ID，否则传递空间ID
	const query = picture.value?.spaceId
		? { id: picture.value.id, spaceId: picture.value.spaceId }
		: { id: picture.value?.id }
	router.push({
		path: `/add_picture`,
		query: query,
	})
}

// 删除
const doDelete = async () => {
	const id = picture.value?.id
	if (!id) {
		message.error('图片ID不存在')
		return
	}

	Modal.confirm({
		title: '⚠️ 危险操作确认',
		icon: createVNode(DeleteOutlined),
		content: `确定要删除这个图片吗？此操作不可恢复，请谨慎操作！\n\n图片名称: ${picture.value?.name}\n图片ID: ${id}`,
		okText: '确认删除',
		okType: 'danger',
		cancelText: '取消',
		width: 400,
		async onOk() {
			const res = await deletePictureUsingPost({ id })
			if (res.data.code === 0) {
				message.success('删除成功')
				router.push('/')
			} else {
				message.error('删除失败：' + res.data.message)
			}
		},
	})
}

// 审核图片 - 显示审核弹窗
const handleReview = async (reviewStatus: number) => {
	currentReviewStatus.value = reviewStatus
	// 设置默认审核信息
	reviewForm.reviewMessage = reviewStatus === PIC_REVIEW_STATUS_ENUM.PASS ? '审核通过' : '审核拒绝'
	reviewModalVisible.value = true
}

// 确认审核操作
const handleReviewConfirm = async () => {
	if (!reviewForm.reviewMessage) {
		message.error('请填写审核意见!')
		return
	}

	reviewModalLoading.value = true
	try {
		const res = await doPictureReviewUsingPost({
			id: picture.value?.id,
			reviewStatus: currentReviewStatus.value,
			reviewMessage: reviewForm.reviewMessage,
		})
		if (res.data.code === 0) {
			message.success('审核操作成功')
			reviewModalVisible.value = false
			// 审核成功后重新获取数据
			fetchPictureDetail()
		} else {
			message.error('审核操作失败：: ' + res.data.message)
		}
	} catch (error) {
		message.error('审核操作失败：，请重试')
	} finally {
		reviewModalLoading.value = false
	}
}

// 取消审核操作
const handleReviewCancel = () => {
	reviewModalVisible.value = false
	reviewForm.reviewMessage = ''
	currentReviewStatus.value = undefined
}

// 处理下载
const doDownload = () => {
	downloadImage(picture?.value?.url)
}

// 分享图片
const shareModalRef = ref()
const shareLink = ref('')
const doShare = () => {
	const loginUser = loginUserStore.loginUser
	// 检查是否登录
	if (!loginUser.id) {
		Modal.confirm({
			title: '需要登录',
			content: '分享图片需要先登录，是否前往登录页面？',
			okText: '去登录',
			cancelText: '取消',
			onOk() {
				router.push(`/user/login?redirect=${window.location.pathname}`)
			},
		})
		return
	}
	// 设置分享链接
	shareLink.value = `${window.location.protocol}//${window.location.host}/picture/${picture.value?.id}`
	if (shareModalRef.value) {
		// 打开分享模态框
		shareModalRef.value.openModal()
	}
}

onMounted(() => {
	// 页面加载时获取数据
	fetchPictureDetail()
})
</script>

<style scoped lang="scss">
#picture-detail-view {
	// 审核弹窗样式
	.review-picture-info {
		display: flex;
		gap: 16px;
		padding: 16px;
		background: #f5f5f5;
		border-radius: 8px;
		margin-bottom: 16px;

		.picture-details {
			flex: 1;

			p {
				margin: 4px 0;
				line-height: 1.5;

				strong {
					color: #262626;
					margin-right: 8px;
				}
			}
		}
	}
}
</style>
